#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: deprecated_app.py
# @time: 2021/3/23 15:33
# @desc:
import json
from fastapi import APIRouter, File, UploadFile, Request, BackgroundTasks

from application.standard_clamp.crud import generate_standard_clamp_data, filter_standard_clamp_under_20, generate_standard_clamp_data_v3
from application.standard_clamp.queryModels import UploadStandardClampModel
from background.background_update import update_03
from cache.redis_pool import get_redis
from models.queryModels import MultipleConditionQueryStandardClamps, UpdateOneStandardClamp
from models.responseModels import ResponseDict, ResponseBool, ResponseStr
from utils.mongo_tools import retrieve_mongo_values, delete_mongo_value, update_mongo_value, create_one_mongo_value, retrieve_one_mongo_value, standard_clamp_number_generator, \
    retrieve_all_mongo_values
from utils.utils import create_folder, write_file, read_json
from views.configs import *
from views.crud import upload_to_aliyun_standard_clamp_model, is_part_in_database, send_to_message_queue, keyword_search_standard_clamp, separate_page, calculate_page, sort_redis_result

standard_clamp_router = APIRouter(
    # prefix="/api/standardclamp",
    prefix="/api/standard_clamp",
    tags=["standard_clamp"],
)


@standard_clamp_router.post("/v4/standard_clamp")
def upload_v4(queryModel: UploadStandardClampModel):
    """
    ## 上传标准夹具接口v4
    - param jsonAliOssAddress: 用户上传的文件路径
    - param desc: 用户需要添加的描述
    - param version: 参数化模型的版本号
    - return:
    """
    number = standard_clamp_number_generator()
    standard_clamp = generate_standard_clamp_data_v3(number, file_path=queryModel.jsonAliOssAddress, desc=queryModel.desc, version=queryModel.version)
    create_one_mongo_value(standard_clamp, collection_name=STANDARD_CLAMP_COLLECTION)
    send_to_message_queue(number)
    update_03()

    model = {"data": number, "status": 1}
    return model


@standard_clamp_router.get("/v2/standard_clamp")
def retrieve_standard_clamp_v2(number: str):
    """
    ## 返回一条标准夹具的完整信息

    - :param number: 编号
    - :return:
    """
    redis_connection = get_redis(port=STANDARD_CLAMP_REDIS_PORT)
    model = {"data": {}}

    # take out the data in redis
    try:
        try:
            standard_clamp = redis_connection.get(number)
            data = json.loads(standard_clamp)
        except:
            # if reach here then means no data in redis. Now go to mongo.
            data = retrieve_one_mongo_value(number, collection_name=STANDARD_CLAMP_COLLECTION)[0]
            # then add it into redis
            redis_connection.set(number, json.dumps(data))
            standard_clamp_number_list = redis_connection.get("standard_clamp")
            standard_clamp_number_list = json.loads(standard_clamp_number_list)
            standard_clamp_number_list.append(number)
            redis_connection.set("standard_clamp", json.dumps(standard_clamp_number_list))
        model["data"] = data

        sort_redis_result(model=model, number=number, data_type="standard_clamp", redis_connection=redis_connection)

        model["status"] = 1
    except:
        model["status"] = 0
    return model


@standard_clamp_router.delete("/v2/standard_clamp", response_model=ResponseBool)
def delete_standard_clamp_v2(number: str, background_task: BackgroundTasks):
    """
    删除一条标准夹具数据。

    - :param number:
    - :return:
    """
    model = {"data": False}
    try:
        result = delete_mongo_value(number, collection_name=STANDARD_CLAMP_COLLECTION)
        background_task.add_task(update_03)
        if result.deleted_count > 0:
            model["data"] = True
            model["status"] = 1
        else:
            model["status"] = 0
    except:
        model["status"] = 0
    return model


@standard_clamp_router.put("/v2/standard_clamp", response_model=ResponseBool)
def update_standard_clamp_v2(queryModel: UpdateOneStandardClamp):
    """
    更新 标准夹具的tag的相关信息

    - :param oneInfo:
    - :return:
    """
    redis_connection = get_redis(port=STANDARD_CLAMP_REDIS_PORT)

    tag = retrieve_all_mongo_values(
        {"number": queryModel.number},
        collection_name=STANDARD_CLAMP_COLLECTION,
    )[0]['tag']
    for i in queryModel.dict().keys():
        if i == "number":
            continue
        if queryModel.dict()[i] is not None:
            tag[i] = queryModel.dict()[i]

    update_mongo_value(
        {"number": queryModel.number},
        {"$set": {"tag": tag}},
        collection_name=STANDARD_CLAMP_COLLECTION,
    )

    try:
        original_data = retrieve_one_mongo_value(queryModel.number, collection_name=STANDARD_CLAMP_COLLECTION)[0]
        redis_connection.set(queryModel.number, json.dumps(original_data))
    except:
        pass

    model = {"data": True, "status": 1}
    return model


@standard_clamp_router.post("/v3/standard_clamps", response_model=ResponseDict)
def multiple_condition_query_standard_clamps_v3(queryModel: MultipleConditionQueryStandardClamps, background_tasks: BackgroundTasks):
    """
    ## 列表查询多条标准夹具。输入参数所有字段均可为空。


    - :param queryModel:
    - :return:
    """
    redis_connection = get_redis(port=STANDARD_CLAMP_REDIS_PORT)

    try:
        standard_clamp_number_list = redis_connection.get("standard_clamp")
        standard_clamp_number_list = json.loads(standard_clamp_number_list)
        standard_clamp_list = redis_connection.mget(*standard_clamp_number_list)
        result = [json.loads(i) for i in standard_clamp_list]
    except:
        result = retrieve_all_mongo_values({}, collection_name=STANDARD_CLAMP_COLLECTION)
        background_tasks.add_task(update_03)

    result = keyword_search_standard_clamp(queryModel, result)
    if len(result) > 0:
        total = len(result)
        result = separate_page(result, page=queryModel.page, pagesize=queryModel.pagesize)
        model = {
            "data": {
                "result": result,
                "total": total,
            },
            "status": 1,
        }
    else:
        model = {"data": {}, "status": 0}
    return model


@standard_clamp_router.get("/v2/standard_clamp_config")
def get_standard_clamp_config_v2():
    """
    ## 获取 标准夹具 版本配置
    原standard_clamp_version接口

    - :return:
    """
    redis_connection = get_redis(port=STANDARD_CLAMP_REDIS_PORT)
    try:
        standard_clamp_config = redis_connection.get("standard_clamp_config")
        config_data = json.loads(standard_clamp_config)
    except:
        config_data = retrieve_all_mongo_values(
            {"type": CONFIG_DATA_STANDARD_CLAMP_TYPE},
            collection_name="config",
        )[0][CONFIG_DATA]
        # 把mongo中查到的数据set到redis数据库中
        redis_connection.set("standard_clamp_config", json.dumps(config_data))

    model = {"data": config_data, "status": 1}
    return model
